<template>
  <div>

    <div class="filter-container hs-bg-card hs-panel">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px" class="filter-item"
                v-model="listQuery.name"> </el-input>
      <el-button class="filter-item" type="primary" icon="search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" v-permission="'client:add'"
                 style="float:right" @click="handleAdd"
                 type="primary" icon="el-icon-plus" circle>
      </el-button>
    </div>

    <div class="hs-bg-card hs-panel mt-2">
      <el-table :data="list" v-loading.body="listLoading"
                border fit
                highlight-current-row
                style="width: 100%; margin: 10px 0;">
        <el-table-column type="index" width="50" label="序号"> </el-table-column>
        <el-table-column width="100" label="ID" prop="clientId">
        </el-table-column>
        <el-table-column label="密码" prop="clientSecret" width="90">
          <template >
            <span>******</span>
          </template>
        </el-table-column>
        <el-table-column width="80" label="范围" prop="scope">
        </el-table-column>
        <el-table-column width="180" label="认证方式" prop="authorizedGrantTypes">
        </el-table-column>
        <el-table-column width="180" label="access_token有效时间" prop="accessTokenValidity">
        </el-table-column>
        <el-table-column width="180" label="refresh_token有效时间" prop="refreshTokenValidity">
        </el-table-column>
        <el-table-column width="90" label="重定向" prop="webServerRedirectUri" >
        </el-table-column>
        <el-table-column width="120" label="autoapprove" prop="autoapprove">
        </el-table-column>

        <el-table-column align="center" label="操作" fixed="right" width="170">
          <template slot-scope="scope">
            <el-button v-permission="'client:decrypt'" size="small" type="text" @click="handleDecrypt(scope.row)">显示密码
            </el-button>
            <el-button v-permission="'client:update'" size="small" type="primary" icon="el-icon-edit" circle @click="handleUpdate(scope.row)">
            </el-button>
            <el-button v-permission="'client:delete'" size="small" type="danger" icon="el-icon-delete" circle @click="handleDelete(scope.row)">
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div v-show="!listLoading && total > 20" class="pagination-container">
        <el-pagination @size-change="handleSizeChange"
                       @current-change="handleCurrentChange"
                       :current-page.sync="listQuery.pageNum"
                       :page-sizes="[20,30,50]"
                       :page-size="listQuery.pageSize"
                       layout="total, sizes, prev, pager, next, jumper"
                       :total="total">
        </el-pagination>
      </div>

    </div>

    <el-dialog :title="textMap[editDialog.type]"
               :visible.sync="editDialog.show">
      <el-form ref="form" :model="form" :rules="rules" label-position="right" label-width="165px">
        <el-form-item label="客户端ID" prop="clientId">
          <el-input v-model="form.clientId" :readonly="editDialog.type === 'add' ? false : 'readonly'" />
        </el-form-item>
        <el-form-item label="秘钥" prop="clientSecret">
          <el-input v-model="form.clientSecret" :readonly="editDialog.type === 'add' ? false : 'readonly'" />
        </el-form-item>
        <el-form-item label="范围" prop="scope">
          <el-input v-model="form.scope" />
        </el-form-item>
        <el-form-item label="认证方式" prop="authorizedGrantTypes">
          <el-select v-model="form.authorizedGrantTypes" multiple value="" placeholder="" style="width:100%">
            <el-option
              v-for="item in grantTypes"
              :key="item.type"
              :label="item.type"
              :value="item.type"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="重定向" prop="webServerRedirectUri">
          <el-input v-model="form.webServerRedirectUri" />
        </el-form-item>
        <el-form-item label="access_token有效时间" prop="accessTokenValidity">
          <el-input v-model="form.accessTokenValidity" />
        </el-form-item>
        <el-form-item label="refresh_token的有效时间" prop="refreshTokenValidity">
          <el-input v-model="form.refreshTokenValidity" />
        </el-form-item>
        <el-form-item label="autoapprove" prop="autoapprove">
          <el-select v-model="form.autoapprove" placeholder="" value="" style="width:100%">
            <el-option label="true" value="1" />
            <el-option label="false" value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel()">取 消</el-button>
        <el-button type="primary" @click="submit()">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { page, addObj, delObj, putObj, decrypt } from 'api/auth/client'

export default {
  name: 'client',
  components: {},
  data () {
    return {
      form: {
        clientId: '',
        resourceIds: '',
        clientSecret: '',
        scope: '',
        authorizedGrantTypes: '',
        webServerRedirectUri: '',
        accessTokenValidity: null,
        refreshTokenValidity: null,
        autoapprove: ''
      },
      rules: {
        clientId: [
          { required: true, message: '请输入客户端ID', trigger: 'blur' },
          { min: 3, max: 20, message: '3-20个字符', trigger: 'blur' }
        ],
        scope: [
          { max: 100, message: 'rules.noMoreThan100', trigger: 'blur' },
          { required: true, message: '请输入授权范围', trigger: 'blur' }
        ],
        // webServerRedirectUri: { validator: (rule, value, callback) => {
        //     if (value !== '' && value != null && !validURL(value)) {
        //       callback(new Error(this.$t('rules.invalidURL')))
        //     } else {
        //       callback()
        //     }
        //   }, trigger: 'blur' },
        clientSecret: [
          { required: true, message: '请输入客户端ID', trigger: 'blur' },
          { min: 6, max: 20, message: '6-20个字符', trigger: 'blur' }
        ],
        accessTokenValidity: [
          { required: true, message: '请输入accessToken有效时间', trigger: 'blur' }
          // { validator: (rule, value, callback) => {
          //     if (!isIntegerGreaterThanZero(value)) {
          //       callback(new Error(this.$t('rules.invalidInteger')))
          //     } else if (value.toString().length > 11) {
          //       callback(new Error(this.$t('rules.noMoreThan11')))
          //     } else {
          //       callback()
          //     }
          //   }, trigger: 'blur' }
        ],
        // refreshTokenValidity: [
        //   { validator: (rule, value, callback) => {
        //       if (value === null || value === '') {
        //         callback()
        //       } else if (!isIntegerGreaterThanZero(value)) {
        //         callback(new Error(this.$t('rules.invalidInteger')))
        //       } else if (value.toString().length > 11) {
        //         callback(new Error(this.$t('rules.noMoreThan11')))
        //       } else {
        //         callback()
        //       }
        //     }, trigger: 'blur' }
        // ],
        authorizedGrantTypes: { required: true, message: '请选择方式', trigger: 'blur' }
      },
      grantTypes: [
        { type: 'refresh_token' },
        { type: 'authorization_code' },
        { type: 'client_credentials' },
        { type: 'password' },
        { type: 'implicit' }
      ],
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        clientId: undefined,
        pageNum: 1,
        pageSize: 20,
        name: undefined
      },
      manage_btn_edit: false,
      manage_btn_del: false,
      manage_btn_add: false,
      manage_btn_secret: false,
      editDialog: {
        type: undefined,
        show: false
      },
      selection: undefined,
      textMap: {
        update: '编辑',
        create: '创建'
      },
      editRoleDialog: {
        clientid: 0,
        name: '',
        show: false
      }
    }
  },
  created () {
    this.getList()
  },
  methods: {
    getList () {
      this.listLoading = true
      page(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter () {
      this.getList().then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    onSelectChange (selection) {
      this.selection = selection
    },
    handleSizeChange (val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.listQuery.pageNum = val
      this.getList()
    },
    handleDecrypt (row) {
      decrypt(row.clientId).then((r) => {
        this.$message.info(r.data)
      })
    },
    handleAdd () {
      this.form.id = 0
      this.editDialog.type = 'add'
      this.editDialog.show = true
    },
    handleUpdate (row) {
      this.form = row
      this.form.id = 1
      this.editDialog.type = 'update'
      this.editDialog.show = true
    },
    handleDelete (row) {
      this.$confirm('此操作将永久删除该用户(' + row.clientId + '), 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delObj(row.clientId).then(() => {
          this.$message.success('删除成功')
          const index = this.list.indexOf(row)
          this.list.splice(index, 1)
        })
      })
    },
    submit () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.authorizedGrantTypes = this.form.authorizedGrantTypes.join(',')
          if (this.form.id > 0) {
            this.update()
          } else {
            this.add()
          }
        }
      })
    },
    add () {
      addObj(this.form).then(response => {
        this.complete(response)
      })
    },
    update () {
      putObj(this.form.id, this.form).then(response => {
        this.complete(response)
      })
    },
    cancel () {
      this.editDialog.show = false
      this.$refs['form'].resetFields()
    },
    complete (response) {
      let success = parseInt(response.code) === 0
      if (!success) {
        return
      }
      this.getList()
      this.cancel()
      this.$message.success('操作成功')
    }
  }
}
</script>
